// 2025/3/8
// https://leetcode.cn/problems/sort-list/?envType=study-plan-v2&envId=top-100-liked
// 排序链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    public:
        ListNode* sortList(ListNode* head) {
            if(head == nullptr || head->next == nullptr) return head;
    
            ListNode phead(0, head);
            ListNode *slow = &phead, *fast = &phead;
            while(fast && fast->next)
            {
                slow = slow->next;
                fast = fast->next->next;
            }
    
            ListNode *left = head, *right = slow->next;
            slow->next = nullptr;
            left = sortList(left);
            right = sortList(right);
            ListNode ret, *cur = &ret;
            while(left && right)
            {
                if(left->val < right->val)
                {
                    cur->next = left;
                    left = left->next;
                }
                else
                {
                    cur->next = right;
                    right = right->next;
                }
                cur = cur->next;
            }
    
            cur->next = left ? left : right;
            return ret.next;
        }
    };